<template>
    <el-tabs v-model="activeTab" type="card">
        <el-tab-pane label="请假申请" name="apply">
            <el-form ref="ruleFormRef" :model="LeaveForm" :rules="rules" label-width="100px"
                class="demo-ruleForm" :size="formSize"
                style="max-width: 600px; padding: 20px; background-color: #f9f9f9; border-radius: 5px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); margin: 0 auto;">
                <!-- 姓名输入框 -->
                <el-form-item label="姓名" prop="name" class="form-item">
                    <el-input v-model="LeaveForm.name" placeholder="请输入你的姓名" clearable
                        :style="{ width: '200px', height: '35px', lineHeight: '35px', borderRadius: '4px' }"
                        @focus="handleInputFocus" @blur="handleInputBlur" />
                </el-form-item>
                <!-- 性别选择框 -->
                <el-form-item label="性别" prop="gender" class="form-item">
                    <el-select v-model="LeaveForm.gender" placeholder="请选择" clearable
                        :style="{ width: '200px', height: '35px', lineHeight: '35px', borderRadius: '4px' }"
                        @focus="handleInputFocus" @blur="handleInputBlur">
                        <el-option label="男" value="1" />
                        <el-option label="女" value="2" />
                    </el-select>
                </el-form-item>
                <!-- 请假原因输入框 -->
                <el-form-item label="请假原因" prop="leaveReason" class="form-item">
                    <el-input v-model="LeaveForm.leaveReason" placeholder="请输入你的请假原因" clearable
                        :style="{ width: '200px', height: '35px', lineHeight: '35px', borderRadius: '4px' }"
                        @focus="handleInputFocus" @blur="handleInputBlur" />
                </el-form-item>
                <!-- 请假类型输入框 -->
                <el-form-item label="请假类型" prop="leaveType" class="form-item">
                    <el-input v-model="LeaveForm.leaveType" placeholder="请输入你的请假类型" clearable
                        :style="{ width: '200px', height: '35px', lineHeight: '35px', borderRadius: '4px' }"
                        @focus="handleInputFocus" @blur="handleInputBlur" />
                </el-form-item>
                <!-- 请假日期选择框 -->
                <el-form-item label="请假日期" prop="leaveDate" class="form-item">
                    <el-date-picker v-model="LeaveForm.leaveDate" type="date" placeholder="请选择当前时间" clearable
                        :style="{ width: '200px', height: '35px', lineHeight: '35px', borderRadius: '4px' }"
                        @focus="handleInputFocus" @blur="handleInputBlur" />
                </el-form-item>
                <!-- 请假天数选择框 -->
                <el-form-item label="请假天数" prop="leaveDays" class="form-item">
                    <el-select-v2 v-model="LeaveForm.leaveDays" placeholder="请选择请假天数" :options="options" clearable
                        :style="{ width: '200px', height: '35px', lineHeight: '35px', borderRadius: '4px' }"
                        @focus="handleInputFocus" @blur="handleInputBlur" />
                </el-form-item>
                <!-- 按钮组 -->
                <el-form-item class="button-group">
                    <el-button type="primary" @click="submitForm(ruleFormRef)"
                        :style="{ marginRight: '10px', height: '35px', lineHeight: '35px' }">申请请假</el-button>
                    <el-button @click="clearLeaveForm"
                        :style="{ height: '35px', lineHeight: '35px' }">清空</el-button>
                </el-form-item>
            </el-form>
        </el-tab-pane>
        <el-tab-pane label="请假记录查询" name="query">
            <el-form :model="searchForm" :inline="true" style="margin-bottom: 10px" class="demo-form-inline">
                <el-form-item label="请假类型">
                    <el-input v-model="searchForm.leaveType" placeholder="请输入请假类型" clearable
                        style="width: 165px" />
                </el-form-item>
                <el-form-item label="请假日期">
                    <el-date-picker v-model="searchForm.leaveDate" value-format="YYYY-MM-DD" type="daterange"
                        placeholder="选择日期范围" range-separator="至" start-placeholder="开始日期"
                        end-placeholder="结束日期" style="width: 250px" />
                </el-form-item>
                <el-form-item label="审批状态">
                    <el-select v-model="searchForm.approveStatus" placeholder="请选择" style="width: 150px">
                        <el-option label="审批中" value="0"></el-option>
                        <el-option label="通过" value="1"></el-option>
                        <el-option label="未通过" value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="fetchLeaveData">查询</el-button>
                    <el-button type="info" style="" @click="resetSearchForm">清空</el-button>
                </el-form-item>
            </el-form>
            <el-table :data="filteredLeaveData" border style="width: 100%; margin: 0 auto;">
                <el-table-column label="请假原因" prop="leaveReason" />
                <el-table-column label="请假类型" prop="leaveType" />
                <el-table-column label="请假日期" prop="leaveDate" />
                <el-table-column label="请假天数" prop="leaveDays" />
                <el-table-column label="审批状态" prop="approveStatus">
                    <template #default="scope">
                        <span v-if="scope.row.approveStatus===0">审批中</span>
                        <span v-if="scope.row.approveStatus===1">通过</span>
                        <span v-if="scope.row.approveStatus===2">未通过</span>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination style="margin-top: 10px" background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="currentPage" :page-sizes="[5, 10, 15, 20]" :page-size="pageSize"
                layout="total, sizes, prev, pager, next" :total="total" />
        </el-tab-pane>
    </el-tabs>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import axios from '@/utils/request';
import { empAccount } from '@/store';
const EmpAccount = ref(empAccount().$state.account)
const activeTab = ref('apply')
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const LeaveForm = ref({
    name: '',
    gender: '',
    account:'',
    leaveReason: '',
    leaveType: '',
    leaveDate: '',
    leaveDays: '',
})
LeaveForm.value.account = EmpAccount.value
const clearLeaveForm = () => {
   LeaveForm.value.account = empAccount().$state.account
    LeaveForm.value.name = '';
    LeaveForm.value.gender = '';
    LeaveForm.value.leaveDate = '';
    LeaveForm.value.leaveReason = '';
    LeaveForm.value.leaveDays = '';
    LeaveForm.value.leaveType = '';
}
const rules = reactive<FormRules>({
    name: [
        { required: true, message: '姓名不能为空', trigger: 'blur' }
    ],
    gender: [
        { required: true, message: '性别不能为空', trigger: 'change', }
    ],
    leaveDate: [
        { required: true, message: '请假日期不能为空', trigger: 'change', type: 'date' }
    ],
    leaveDays: [
        { required: true, message: '请假天数不能为空', trigger: 'change', }
    ],
    leaveReason: [
        { required: true, message: '请假原因不能为空', trigger: 'blur' }
    ],
    leaveType: [
        { required: true, message: '请假类型不能为空', trigger: 'blur' }
    ]
})

// 处理输入框获取焦点事件，添加获取焦点时的样式类
const handleInputFocus = () => {
    const inputElements = document.querySelectorAll('.form-item input,.form-item select');
    inputElements.forEach(element => {
        element.classList.add('input-focused');
    });
}

// 处理输入框失去焦点事件，移除获取焦点时的样式类
const handleInputBlur = () => {
    const inputElements = document.querySelectorAll('.form-item input,.form-item select');
    inputElements.forEach(element => {
        element.classList.remove('input-focused');
    });
}

// 提交请假申请表单
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 发送POST请求到后端接口，提交请假申请数据
            axios.post('/emp/leave', LeaveForm.value)
              .then(response => {
                    if (response.data.code===1) {
                        // 后端接口返回成功，重置表单
                        formEl.resetFields();
                        ElMessage({
                            message: '表单提交成功！',
                            type: 'success',
                            duration: 2000
                        });
                        // 重新获取请假记录数据，刷新表格显示
                        fetchLeaveData();
                        // 切换到查询标签页，方便查看提交的数据
                        activeTab.value = 'query'
                    } else {
                        ElMessage({
                            message: '表单提交失败，请稍后重试！',
                            type: 'error',
                            duration: 2000
                        });
                    }
                })
              .catch(error => {
                    console.error('提交请假申请出错：', error);
                    ElMessage({
                        message: '网络错误，请检查网络连接或联系管理员！',
                        type: 'error',
                        duration: 2000
                    });
                });
        } else {
            console.log('error submit!', fields);
            ElMessage({
                message: '请检查表单填写是否完整！',
                type: 'warning',
                duration: 2000
            });
        }
    })
}
const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))

// 请假数据相关
const searchForm = reactive({
    leaveType: '',
    leaveDate:['',''],
    approveStatus: ''
})
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const filteredLeaveData = ref([])

// 分页尺寸改变时的处理函数
const handleSizeChange = (size: number) => {
    pageSize.value = size
    fetchLeaveData()
}

// 当前页码改变时的处理函数
const handleCurrentChange = (page: number) => {
    currentPage.value = page
    fetchLeaveData()
}

// 获取请假记录数据的函数，从后端接口获取数据
const fetchLeaveData = async () => {
    try {
        const response = await axios.get('/emp/leave', {
            params: {
                page: currentPage.value,
                pageSize: pageSize.value,
                account: EmpAccount.value,
                leaveType: searchForm.leaveType,
                startDate: searchForm.leaveDate[0],
                endDate: searchForm.leaveDate[1],
                approveStatus: searchForm.approveStatus
            }
        });
        if (response.data.code === 1) {
            filteredLeaveData.value= response.data.data.rows
            total.value = response.data.data.total
            if(searchForm.leaveType!==''||searchForm.leaveDate[0]!==''||searchForm.leaveDate[1]!==''||searchForm.approveStatus!==''){
                ElMessage({
                    message: '查询成功！',
                    type: 'success',
                    duration: 2000
                });
            }
        } else {
            ElMessage({
                message: '获取请假记录失败，请稍后重试！',
                type: 'error',
                duration: 2000
            });
        }
    } catch (error) {
        console.error('获取请假记录出错：', error);
        ElMessage({
            message: '网络错误，请检查网络连接或联系管理员！',
            type: 'error',
            duration: 2000
        });
    }
}

const resetSearchForm = () => {
    searchForm.leaveType = ''
    searchForm.leaveDate = ['', '']
    searchForm.approveStatus = ''
    fetchLeaveData()
}
onMounted(() => {
    fetchLeaveData();
    LeaveForm.value.account = EmpAccount.value
    LeaveForm.value.name = empAccount().$state.name;
    LeaveForm.value.gender = empAccount().$state.gender=='1'?'1':'2';
})
</script>

<style scoped>
body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    padding: 20px;
}

.form-item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
}

.button-group {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}

/* 输入框获取焦点时的样式 */
.input-focused {
    border-color: #409EFF!important;
    box-shadow: 0 0 5px rgba(64, 158, 255, 0.5)!important;
}

.demo-form-inline {
    display: flex;
    align-items: center;
    justify-content: center;
}

.el-tabs {
    border-radius: 10px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    background-color: white;
    padding: 20px;
}

.el-tabs__item {
    padding: 10px 20px;
    font-size: 16px;
    color: #333;
}

.el-button {
    border-radius: 4px;
    transition: all 0.3s ease;
}

.el-button:hover {
    opacity: 0.8;
}

.el-table {
    border: 1px solid #ebeef5;
    border-radius: 4px;
    overflow: hidden;
    margin-top: 10px;
}

.el-table th,
.el-table td {
    padding: 8px 10px;
    text-align: center;
}

.el-pagination {
    margin-top: 10px;
    text-align: right;
}
</style>